<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class GoodsController extends Controller
{
    //商品添加页面
    public function add(Request $request)
    {
        $title = '商品管理';

        //会话跟踪
        $staff = $request->session()->get('staff');

        $data = DB::table('bro_cate') -> where('pid','=','0') -> get();
        $brand = DB::table('bro_brand') -> get();
        return view('admin.goods.add',['title' => $title,'data' => $data,'staff' => $staff,'brand' => $brand]);


    }
    //商品添加
    public function insert(Request $request)
    {   //获取添加页面提交上来的数据,并去除了'_token'隐藏的数据'
        $data = $request -> except('_token');
        //商品发布时间;
        $data['ptime'] = time();
        $data['goods_num'] = 'JD'.time().rand(10000,99999);
        $data['price'] = $data['price'].'.00';
        $data['size'] = implode(',', $data['size']);
        $data['color'] = implode(',',$data['color']);
        // dd($data);
        if($request -> hasFile('goods_pic'))//判断是否有文件
        {
            if($request -> file('goods_pic') -> isValid())//判断文件是否有效
            {
                $arr = array('jpg','png','gif');

                //获取文件的后缀名
                $suffix = $request -> file('goods_pic') -> getClientOriginalExtension();

                //判断上传文件是否是图片
                if(in_array($suffix,$arr))
                {
//                    $fileName = time().rand().'.'.$suffix;


                    $fileName = time().rand().'.'.$suffix;

                    $category_id = $data['category_id'];

                    $data['goods_pic'] = '/uploads/goods/'.$category_id.'/'.$fileName;

                    //上传文件
                    $path = './uploads/goods/'.$category_id;//上传文件的目录
                    //执行上传
                    $request -> file('goods_pic') -> move($path,$fileName);

                    //拼凑goods_pic的URL地址
//                    $data['goods_pic'] = trim($path.'/'.$category_id.'/'.$fileName,'.');

                    $res = DB::table('bro_goods') -> insert($data);

                }else
                {
                    return redirect('/admin/goods/add') -> with('error','上传文件不合法');
                }
            }
        }
        return redirect('/admin/goods/show') -> with('success','添加成功');
    }
    //商品列表
    public function show(Request $request)
    {
        $title = '商品列表';

        //会话跟踪
        $staff = $request->session()->get('staff');

//        $data = DB::table('bro_goods')->paginate(1);
        $data = DB::table('bro_goods') ->where(function($query) use ($request){
            $query -> where('goods_name','like','%'.$request -> input('keywords').'%');
        }) -> paginate($request -> input('num',5));

        return view('admin.goods.show',['title' => $title,'data' => $data,'request' => $request -> all(),'staff' => $staff]);


        //会话跟踪
        $staff = $request->session()->get('staff');

        $data = DB::table('bro_goods')->get();
        

        return view('admin.goods.show',['title' => $title,'data' => $data,'staff'=>$staff]);

        
    }
    
    //商品详情
    public function edit(Request $request,$id)
    {
//        dd($id);
        $title = '商品详情';

        //会话跟踪
        $staff = $request->session()->get('staff');
        
        //查询所有分类
        $cate = DB::table('bro_cate')
            -> select('*',DB::raw("concat(path,',',id) as sort_str"))
            -> orderBy('sort_str','asc')
            -> get();
        foreach($cate as $k => $v){
            //拆分数组
            $arr = explode(',',$v->path);
            //统计数组的元素个数
            $num = count($arr);
            //重复字符串
            $str = str_repeat('-->',$num -1);
            //修改name名称
            $cate[$k] -> catename = $str.$v -> catename;
        }

        $data = DB::table('bro_goods') -> where('id','=',$id) -> get();
        return view('admin.goods.edit',['title' => $title,'cate' => $cate,'data' => $data,'staff'=>$staff]);
    }

    //商品修改
    public function update(Request $request)
    {

        $data = $request -> except('_token','oldpic');

        if($request -> hasFile('goods_pic'))//判断是否有文件
        {
            if($request -> file('goods_pic') -> isValid())//判断文件是否有效
            {
                $arr = array('jpg','png','gif');
                //获取文件的后缀名
                $suffix = $request -> file('goods_pic') -> getClientOriginalExtension();

                //判断上传文件是否是图片
                if(in_array($suffix,$arr))
                {

                    $fileName = time().rand().'.'.$suffix;

                    $category_id = $data['category_id'];

                    $data['goods_pic'] = '/uploads/goods/'.$category_id.'/'.$fileName;
                    
                    //上传文件
                    $path = './uploads/goods/'.$category_id;//上传文件的目录

                    //执行上传
                    $request -> file('goods_pic') -> move($path,$fileName);

                    $oldpath = '.'.$request -> input('oldpic');

                    if($oldpath != '.' )
                    {
                        if(file_exists($oldpath))
                        {
                            unlink($oldpath);
                        }
                    }

                }else{
                    return back() -> with('error','上传文件不合法');
                }

            }
            $data = DB::table('bro_goods') -> where('id',$data['id']) -> update($data);
        }


        if($data)
        {
            return redirect('/admin/goods/show') -> with('success','更新成功');
        }else{
            return back() -> with('error','更新失败');
        }
    }

    //商品删除
    public function delete($id)
    {
        $goods_pic = DB::table('bro_goods') -> where('id',$id) -> first() -> goods_pic;
        $oldpath = '.'.$goods_pic;

        if($oldpath != '.')
        {
            if(file_exists($oldpath))
            {
                unlink($oldpath);
            }
        }
        $res = DB::table('bro_goods') -> where('id',$id) -> delete();
        //判断是否删除成功
        if($res)
        {
            return redirect('/admin/goods/show') -> with('success','删除成功');
        }else{
            return back() -> with('error','删除失败');
        }
    }
    //ajax分类联动
    public function ajaxCate(Request $request)
    {

        $id = $request -> all();

        $a = DB::table('bro_cate') -> where('pid','=',$id) -> get();
        return response() -> json($a);

    }

    //ajax
    public function ajax(Request $request)
    {

        $id = $request -> all();

        $a = DB::table('bro_goods') -> where('id','=',$id) -> first();
        if($a -> tuijian == 1)
        {
           DB::table('bro_goods') -> where('id','=',$id) -> update(['tuijian' => 0]);
            $b = 0;
        }else{
            DB::table('bro_goods') -> where('id','=',$id) -> update(['tuijian' => 1]);
            $b = 1;
        }

        $ab = DB::table('bro_goods') -> where('id','=',$id) -> first();

        return response() -> json($b);

    }
    //图像管理
    public function goodspic(Request $request,$id)
    {
        $title = '图像管理';
        //会话跟踪
        $staff = $request->session()->get('staff');
        $data = DB::table('bro_goods') -> select('describe') -> where('id','=',$id) ->first();
        $pic = get_object_vars($data)['describe'];


        preg_match_all("/\/uploads\/.*?\.jpg/",$pic,$match); //这里是关键
//        dd($match[0]);



        return view('admin.goods.goodspic',['title' => $title,'match' => $match[0],'staff' => $staff]);
    }

    
}
